package com.meiyou.controller;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.meiyou.pojo.Coordinate;
import com.meiyou.pojo.EasyUIDataGrid;
import com.meiyou.pojo.MeiyouEvaluate;
import com.meiyou.pojo.MeiyouPtjls;
import com.meiyou.pojo.MeiyouTnask;
import com.meiyou.pojo.MeiyouTuina;
import com.meiyou.service.AppSettingService;
import com.meiyou.service.EvaContentService;
import com.meiyou.service.PtjlsService;
import com.meiyou.service.TuiNaService;
import com.meiyou.service.UserService;
import com.meiyou.utils.Context;
import com.meiyou.utils.Msg;
import com.meiyou.utils.PagesMap;
import com.meiyou.utils.jedis.JedisClient;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import redis.clients.jedis.GeoRadiusResponse;

@Controller
@Api(value = "美游app控制器", tags = { "所有api接口" })
public class TuiNaController {
	@Resource
	private TuiNaService tuiNaServiceImpl;
	@Resource
	private AppSettingService appsetting;
	@Resource
	private PtjlsService ptjlsServiceImpl;
	@Resource
	private UserService userServiceImpl;
	@Resource
	private JedisClient jedisClient;
	@Resource
	private EvaContentService evaContentServiceImpl;

	@RequestMapping(value = "insTuiNa", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "发布推拿会所")
	public Msg Fabu(@RequestParam("mfile") MultipartFile[] mfile,String tName,String tAddress,String tProduce,Integer tMeijin,Integer tMsmeijin,
		Integer tZdtime,double jindu,double weidu,HttpServletRequest request ,double ZhiDingfei,String pay){
		if(request.getSession().getAttribute("user")==null) {
			System.out.println("session值位空");
			Msg.fail();
		}else {
		String uCount = request.getSession().getAttribute("user")+"";
		double meijin = Double.parseDouble(userServiceImpl.selUserByUcount(uCount));
		System.out.println(meijin);
		String num=appsetting.selFaBuJin();
		int fabujin=Integer.parseInt(num);
		System.out.println(fabujin);
		if(meijin>=fabujin+ZhiDingfei){
			String payword = userServiceImpl.selUserPayByUcount(uCount);
			System.out.println(payword);
			if(pay!=null&&pay.equals(payword)){
				//这里mfile可以接受前台的文件，可以是一个，也可以是多个，这正是MultipartFile强大的地方。
				HashMap<String, String> map=new HashMap<String, String>();
				//建一个Map便于返回json
				String filePath =null;
				String fileName[]=new String[mfile.length];
				Date date=new Date();
				//根据传递文件个数返回文件（{msg1:"sss.png",msg2:"aa.jpg"}
				String file = "[";
				if (mfile != null && mfile.length > 0) {
				//判断使用有文件上传
					for (int i = 0; i < mfile.length; i++) {
						//循环上传（多文件上传）
						try {
							Calendar cale = null;	
							cale = Calendar.getInstance();
							int year = cale.get(Calendar.YEAR);
							int month = cale.get(Calendar.MONTH) + 1;
							int day = cale.get(Calendar.DATE);
							String address = Context.fwqaddress;
							//给图片重命名加上日期前缀
							filePath= request.getSession().getServletContext().getRealPath("/") ;
							//获取服务器img文件夹地址（这里指的是local:8080/项目名/img）
							fileName[i]= "/imgs/" + year + ""+ month + "" + day + "_" + mfile[i].getOriginalFilename();
							//重命名图片。
							String type = fileName[i].substring(fileName[i].lastIndexOf(".")+1, fileName[i].length());
							//截取文件后缀判断是否是一张图片
							if((type.equals("png"))||(type.equals("jpg"))||(type.equals("jpeg"))){
								int length = mfile[i].getBytes().length;
								if (!((length / 1000) > 5120)) {
									
									//判断图片地址
									map.put("msg"+i, fileName[i]);
									//将图片输出到制定的文件夹目录中
									mfile[i].transferTo(new File(filePath,fileName[i]));
									if(i==mfile.length-1){
										file +="\""+address+fileName[i]+"\"]";
									}else{
										file +="\""+address+fileName[i]+"\",";
									}
								}else{
									map.put("msg", "图片过大");
								}}else{
								map.put("msg", "只能上传图片啊亲!");}
						} catch (Exception e) {
							e.printStackTrace();
							map.put("msg", "上传失败");}}} else {
					map.put("msg", "请选择文件");}
				MeiyouTuina meiyouTuina = new MeiyouTuina();
				meiyouTuina.settTime(date);
				meiyouTuina.settState("已发布");
				meiyouTuina.settUCount(uCount);
				meiyouTuina.settAddress(tAddress);
				meiyouTuina.settImg(file);
				meiyouTuina.settMeijin(tMeijin);
				meiyouTuina.settMsmeijin(tMsmeijin);
				meiyouTuina.settZdtime(tZdtime);
				meiyouTuina.settProduce(tProduce);
				meiyouTuina.settName(tName);
				int index=tuiNaServiceImpl.insTuiNa(meiyouTuina);

				System.out.println("id为"+index);

				Coordinate coordinate = new Coordinate();
				coordinate.setLatitude(weidu);
				coordinate.setLongitude(jindu);
				coordinate.setKey(meiyouTuina.gettId()+"");
				jedisClient.addReo(coordinate,"tuina");

				if(index>0){
					MeiyouPtjls meiyouPtjls=new MeiyouPtjls();
					meiyouPtjls.setpMeijin(fabujin);
					meiyouPtjls.setpTime(date);
					meiyouPtjls.setpUCount(uCount);
					int ptjls = ptjlsServiceImpl.insPtjls(meiyouPtjls);
					double uMeijin=meijin-(ZhiDingfei+fabujin);
					int upd = userServiceImpl.updUserMeijin(uMeijin,uCount);
					if(ptjls>0 && upd>0){
						return Msg.success();
					}
				}
			}else {
				return Msg.fail();
			}
		}else{
			return Msg.fail();
		}
		}
		return Msg.success();
	}
		

	@RequestMapping(value = "selTuiNa", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "显示推拿会所全部信息")
	public List<MeiyouTuina> selTuiNa(HttpServletRequest request) {
		 String tUCount = request.getSession().getAttribute("user")+"";
		 List<MeiyouTuina> selTuina = tuiNaServiceImpl.selTuina(tUCount);
		 for(MeiyouTuina meiyouTuina:selTuina){
			 JSONArray array = JSONArray.parseArray(meiyouTuina.gettImg());
		     meiyouTuina.setArray(array);
		 }
		 return selTuina;
	}
	
	@RequestMapping(value = "/delTuiNa", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "删除推拿会所个人信息")
	public int delTuiNa(int tId){
		return tuiNaServiceImpl.delTuiNa(tId);
	}
	
	@RequestMapping(value = "/showTuiNa", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "后台分页显示推拿会所信息")
	public Msg showTuiNa(int pn,MeiyouTuina meiyouTuina){
		List<MeiyouTuina> list = tuiNaServiceImpl.showTuiNa(meiyouTuina);
		Map<String, Object> map = PagesMap.getpagesTuiNaMaps(list, pn);
		return Msg.success().add("pageInfo", map);
	}
	
	@RequestMapping(value = "selectAllTuiNa", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "后台分页模糊显示推拿会所信息")
	public EasyUIDataGrid selectAllTuiNa(String tUCount,int rows,int page){
		return tuiNaServiceImpl.selectAllTuiNa(tUCount, rows, page);
	}

	@RequestMapping(value = "tuinaApply", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "购买推拿服务")
	public Msg TuinaApply(String uCount,String pay,int tId){
		double meijin = Double.parseDouble(userServiceImpl.selUserByUcount(uCount));
		String payword = userServiceImpl.selUserPayByUcount(uCount);
		if(payword!=null&&!payword.equals("")&&payword.equals(pay)){
			int Apply=1;
			double uMeijin=meijin-Apply;
			int upd = userServiceImpl.updUserMeijin(uMeijin, uCount);
			Date date = new Date();
			MeiyouPtjls meiyouPtjls=new MeiyouPtjls();
			meiyouPtjls.setpMeijin(Apply);
			meiyouPtjls.setpTime(date);
			meiyouPtjls.setpUCount(uCount);
			int ptjls = ptjlsServiceImpl.insPtjls(meiyouPtjls);
			if(ptjls>0&&upd>0){
				MeiyouTnask meiyouTnask = new MeiyouTnask();
				meiyouTnask.settTId(tId);
				meiyouTnask.settState("购买成功");
				meiyouTnask.settTime(date);
				meiyouTnask.settUCount(uCount);
				int index = tuiNaServiceImpl.insTnask(meiyouTnask);
				if(index>0){
					int tSell = tuiNaServiceImpl.selSell(tId);
					tSell+=1;
					tuiNaServiceImpl.updSell(tSell,tId);
				    return Msg.success();
				}else {
					return Msg.fail();
				}
			}
		}
		else{
			return Msg.fail();
		}
		return Msg.fail();
	}
	//根据登录用户经纬度查询附近服务
		@RequestMapping(value="/selService",method=RequestMethod.POST)
		@ResponseBody
		@ApiOperation(value="根据经纬度查询服务",notes="根据经纬度查询服务",httpMethod="POST")
		public Msg selectdongtai(double jindu,double weidu,HttpServletRequest req){
			if(req.getSession().getAttribute("user")==null) {
				System.out.println("session值位空");
				Msg.fail();
			}else {
		    String uCount = req.getSession().getAttribute("user")+"";
			System.out.println(jindu+"||"+weidu+"||"+uCount); 
			Coordinate coordinate = new Coordinate();
			coordinate.setLatitude(weidu);
			coordinate.setLongitude(jindu);
			List<GeoRadiusResponse> list = jedisClient.geoQuery(coordinate, 100,"tuina");
			List<Object> ls = new ArrayList<Object>();
			if(list!=null && list.size()!=0) {
				for(GeoRadiusResponse geo:list) {
					System.out.println(geo.getMemberByString());
					MeiyouTuina tuinaTemp = tuiNaServiceImpl.selTuinaById(Integer.parseInt(geo.getMemberByString()));
					MeiyouTuina meiyouTuina=new MeiyouTuina();
					Map<String,Object> map = new HashMap<String,Object>();
					if(tuinaTemp!=null) {
						//是本人就不显示
						if(!uCount.equals(tuinaTemp.gettUCount())) {
							BeanUtils.copyProperties(tuinaTemp, meiyouTuina);
						    DecimalFormat    df   = new DecimalFormat("######0.00");
						    String juli = df.format(geo.getDistance());
						    System.out.println(juli);
						    map.put("tId", tuinaTemp.gettId());
						    map.put("tImg", tuinaTemp.gettImg());
						    map.put("tAddress", tuinaTemp.gettAddress());
						    map.put("tMeijin", tuinaTemp.gettMeijin());
						    map.put("tMsmeijin", tuinaTemp.gettMsmeijin());
						    map.put("tName", tuinaTemp.gettName());
						    map.put("tProduce", tuinaTemp.gettProduce());
						    map.put("tSell", tuinaTemp.gettSell());
						    map.put("tAssess", tuinaTemp.gettAssess());
						    map.put("juli", juli+"km");
						    ls.add(map);
						}
					}
				}	
				return Msg.success().add("list", ls);
			}
			else {
				return Msg.success().add("msg", "暂时没有附近服务");  
			}
			}
			return Msg.fail().add("msg", "未登录");
		}
		
		@RequestMapping(value = "selTuinaDetails", method = RequestMethod.POST)
		@ResponseBody
		@ApiOperation(value = "推拿详情")
		public MeiyouTuina selTuinaDetails(int tId){
			 MeiyouTuina selTuinaDetails = tuiNaServiceImpl.selTuinaDetails(tId);
			 JSONArray array=JSONArray.parseArray(selTuinaDetails.gettImg());
			 selTuinaDetails.setArray(array);
			 return selTuinaDetails;
		}
		@RequestMapping(value = "tnPingxing", method = RequestMethod.POST)
		@ResponseBody
		@ApiOperation(value = "推拿评星")
		public Msg tnPingxing(int tAssess,int tId,String eUBcount,HttpServletRequest request){
			String eUCount = request.getSession().getAttribute("user")+"";
			Date date = new Date();
			MeiyouEvaluate meiyouEvaluate = new MeiyouEvaluate();
			int assess = tuiNaServiceImpl.selTuinaAssess(tId);
			if(assess==0){
				tuiNaServiceImpl.updTuinaAssess(tAssess, tId);
				meiyouEvaluate.setContent(Integer.toString(tAssess));
				meiyouEvaluate.seteUBcount(eUBcount);
				meiyouEvaluate.setTime(date);
				meiyouEvaluate.seteUCount(eUCount);
				meiyouEvaluate.settId(tId);
				evaContentServiceImpl.insEvaluate(meiyouEvaluate);
				return Msg.success();
			}else {
				tAssess=(assess+tAssess)/2;
				tuiNaServiceImpl.updTuinaAssess(tAssess, tId);
				meiyouEvaluate.setContent(Integer.toString(tAssess));
				meiyouEvaluate.seteUBcount(eUBcount);
				meiyouEvaluate.setTime(date);
				meiyouEvaluate.seteUCount(eUCount);
				meiyouEvaluate.settId(tId);
				evaContentServiceImpl.insEvaluate(meiyouEvaluate);
				return Msg.success();
			}
		}
}
